import { ConfigEnv, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import createStyleImportPlugin, { VxeTableResolve } from 'vite-plugin-style-import';
import path from 'path';
import _ from 'lodash';

function parseEnv(env: Record<string, any>): extraViteEnv {
  const cloneDeep_env: any = _.cloneDeep(env);
  Object.entries(env).forEach(([key, value]) => {
    if (value === 'true' || value === 'false') cloneDeep_env[key] = value === 'true' ? true : false;
    else if (/^\d+$/.test(value)) cloneDeep_env[key] = Number(value);
    else if (value === 'null') cloneDeep_env[key] = null;
    else if (value === 'undefined') cloneDeep_env[key] = undefined;
  });
  return cloneDeep_env;
}

export default ({ command, mode }: ConfigEnv) => {
  const isBuild = command === 'build';
  const isProd = mode === 'production';
  const root = process.cwd();
  const env = parseEnv(loadEnv(mode, root));

  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router', 'pinia'],
        dts: 'types/auto-imports.d.ts',
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        dirs: ['src/components'],
        //组件名称包含目录，防止同名组件冲突
        directoryAsNamespace: true,
        //指定类型声明文件，为true时在项目根目录创建
        dts: 'types/components.d.ts',
      }),
      createStyleImportPlugin({
        resolves: [VxeTableResolve()],
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    optimizeDeps: {
      include: ['element-plus/lib/locale/lang/zh-cn', 'element-plus/lib/locale/lang/en'],
    },
    server: {
      open: true,
      proxy: {
        '/api': {
          ws: true,
          target: env.VITE_PROXY_TARGET,
          changeOrigin: true,
        },
      },
    },
    build: {
      outDir: 'dist',
      sourcemap: false,
      rollupOptions: {
        emptyOutDir: true,
      },
    },
  };
};
